<template>
  <el-dialog :model-value="props.modelValue" @update:model-value="emit('update:modelValue', $event)" title="选择客户"
    width="80%" draggable>
    <el-form :model="searchForm" inline class="search-bar">
      <el-form-item>
        <el-tree-select v-model="searchForm.type" :data="treeSelectData" filterable clearable style="width: 240px"
          :props="{ value: 'id', label: 'name', children: 'children' }" :check-strictly="true" placeholder="类别"
          @node-click="handleNodeClick">
          <template #default="{ data }">
            <span>
              <el-icon>
                <Folder v-if="data.children && data.children.length > 0" />
                <Document v-else />
              </el-icon>
              {{ data.name }}
            </span>
          </template>
        </el-tree-select>
      </el-form-item>

      <el-form-item>
        <el-input v-model="searchForm.keyword" placeholder="输入编号/名称/联系人/电话查询" style="width: 300px" />
      </el-form-item>

      <el-form-item>
        <el-checkbox v-model="searchForm.status" @change="handleCheck">显示禁用客户</el-checkbox>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="searchCustomer">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%" border :header-cell-style="{ 'background-color': '#f5f7fa' }"
      @selection-change="handleSelectionChange" highlight-current-row v-loading="tableLoad" height="400px">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="typeName" label="类别" width="120" />
      <el-table-column prop="code" label="编号" width="120" sortable />
      <el-table-column prop="name" label="名称" width="180" sortable />
      <el-table-column prop="primaryContactName" label="联系人" width="120" />
      <el-table-column prop="primaryContactPhone" label="手机" width="150" />
      <el-table-column prop="primaryContactAddress" label="地址" width="150" />
      <el-table-column prop="remark" label="备注" />
    </el-table>

    <div class="pagination" v-if="total > 0">
      <el-pagination v-model:current-page="pageInfo.pageNum" v-model:page-size="pageInfo.pageSize"
        :page-sizes="[5, 10, 15, 20]" :background="true" layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <template #footer>
      <el-button type="primary" @click="showAddCustomer = true">新增客户</el-button>

      <AddCustomerDialog V-model="showAddCustomer" @confirm="handleAddCustomer"/>
      <div class="right-buttons">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, defineProps, defineEmits, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios';
import AddCustomerDialog from './AddCustomerDialog.vue';

// 接收父组件传递的客户列表和客户类别数据
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
});

const emit = defineEmits(['update:modelValue', 'confirm']);

const showAddCustomer = ref(false)

const handleAddCustomer = () => {
   getCustomerList()
}

// 状态管理
const tableLoad = ref(false);

// 搜索表单
const searchForm = ref({
  type: null,
  keyword: '',
  status: 1,
});

const pageInfo = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
})

// 客户数据
const tableData = ref([])

// 获取客户信息
const getCustomerList = async () => {
  tableLoad.value = true
  try {
    const params = {
      pageNum: pageInfo.pageNum,
      pageSize: pageInfo.pageSize,
      ...searchForm.value
    }

    const res = await axios.get('/api/basic/customer/customerByPage', { params })
    if (res.data.code === 5200) {
      tableData.value = res.data.pageInfo.list
      pageInfo.total = res.data.pageInfo.total
      pageInfo.pageNum = res.data.pageInfo.pageNum
    } else {
      ElMessage.error(res.data.message)
    }
  } catch (error) {
    console.error('加载客户列表失败:', error)
    ElMessage.error('加载客户列表失败: ' + (error.response?.data?.msg || error.message))
  } finally {
    tableLoad.value = false
  }
}


// 客户类别数据
const customerTypeList = ref([])

// 获取客户类别
const getCustomerType = async () => {
  const res = await axios.get('/api/basic/customer/allCustomerTypes')
  if (res.data.code === 5200) {
    customerTypeList.value = res.data.customerTypeList
  }
}

// 构建树形数据
const treeData = computed(() => {
  const roots = []

  const map = {}

  customerTypeList.value.forEach(item => {
    map[item.id] = { ...item, children: [] }
  })

  customerTypeList.value.forEach(item => {
    if (item.parentId == null || item.parentId == '0') {
      roots.push(map[item.id])
    } else {
      const parentObj = map[item.parentId]
      if (parentObj) {
        parentObj.children.push(map[item.id])
      }
    }
  })
  return roots
})

const treeSelectData = computed(() => {
  const enabledTreeData = treeData.value
  return [
    {
      id: '0',
      name: '全部',
      children: enabledTreeData
    }
  ]
})

const searchCustomer = () => {
  pageInfo.pageNum = 1;
  getCustomerList()
};

const handleCheck = (checked) => {
  searchForm.value.status = checked ? null : 1
  getCustomerList()
}

const handleSizeChange = (size) => {
  pageInfo.pageSize = size
  pageInfo.pageNum = 1
  getCustomerList()
};
const handleCurrentChange = (page) => {
  pageInfo.pageNum = page
  getCustomerList()
};

const handleNodeClick = (data) => {
  searchForm.value.type = data.id === '0' ? null : data.id
  pageInfo.pageNum = 1
  getCustomerList()
}

const selectedCustomers = ref([])

const handleSelectionChange = (selection) => {
  selectedCustomers.value = selection
}

const handleConfirm = () => {
  if (selectedCustomers.value.length === 0) {
    ElMessage.warning('请选择至少一个客户')
    return
  }
  emit('confirm', [...selectedCustomers.value])
  closeDialog()
}

const closeDialog = () => {
  emit('update:modelValue', false)
}

watch(() => props.modelValue, (isOpen) => {
  if (isOpen) {
    searchForm.value = { keyword: '', type: null, status: 1 }
    pageInfo.pageNum = 1
    getCustomerType()
    getCustomerList()
  }
})

</script>

<style scoped>
.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.pagination {
  margin-top: 15px;
  text-align: right;
  display: flex;
  justify-content: right;
}

:deep(.el-table .el-table__header th) {
  background-color: #f5f7fa !important;
}
</style>